<template>
  <div class="flex-1 min-h-0 overflow-hidden">
    <n-data-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :pagination="pagination"
      :bordered="false"
      :single-line="false"
      :loading="loading"
      :scroll-x="4000"
      size="small"
      striped
      @scroll="handleTableScroll"
      flex-height
      class="h-full"
    />
  </div>
</template>

<script setup>
import { ref, h, computed } from 'vue'
import { useRouter } from 'vue-router'
import { NDataTable, NSpace, NButton, NIcon, NTooltip, NTag, useDialog, useMessage } from 'naive-ui'
import { Trash as TrashIcon } from '@vicons/tabler'

const props = defineProps({
  tableData: {
    type: Array,
    default: () => []
  },
  pagination: {
    type: Object,
    default: () => ({})
  },
  loading: {
    type: Boolean,
    default: false
  },
  baseColumns: {
    type: Array,
    default: () => []
  },
  visibleColumns: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['view-details', 'delete-member', 'table-scroll'])

const router = useRouter()
const dialog = useDialog()
const message = useMessage()
const tableRef = ref(null)

// 表格列计算属性 - 处理特殊渲染和操作列
const columns = computed(() => {
  const actionColumn = {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    width: 150,
    render(row) {
      return h(NSpace, { size: 'small' }, {
        default: () => [
          h(NButton, {
            size: 'small',
            type: 'primary',
            onClick: () => handleViewDetails(row)
          }, { default: () => '查看详情' }),
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteMember(row)
          }, { 
            default: () => '删除',
            icon: () => h(NIcon, null, { default: () => h(TrashIcon) })
          })
        ]
      })
    }
  }

  return props.baseColumns
    .filter(col => props.visibleColumns.includes(col.key))
    .map(col => {
      if (col.key === 'actions') {
        return actionColumn
      }

      // 处理长文本字段的省略显示
      if (['memberRemarks', 'majorField', 'currentPartyBranch', 'birthPlace'].includes(col.key)) {
        return {
          ...col,
          render(row) {
            const text = row[col.key] || '-'
            if (text.length > 10) {
              return h(NTooltip,
                { trigger: 'hover' },
                {
                  trigger: () => text.substring(0, 10) + '...',
                  default: () => text
                }
              )
            }
            return text
          }
        }
      }

      // 处理计数字段的标签显示
      if (col.key.includes('Count')) {
        return {
          ...col,
          render(row) {
            const count = row[col.key] || 0
            return h(NTag, {
              type: count > 0 ? 'success' : 'default',
              size: 'small'
            }, { default: () => count })
          }
        }
      }

      // 处理身份证号脱敏显示
      if (col.key === 'idCardNumber') {
        return {
          ...col,
          render(row) {
            const idCard = row[col.key] || ''
            if (idCard.length === 18) {
              return idCard.substring(0, 6) + '******' + idCard.substring(14)
            }
            return idCard || '-'
          }
        }
      }

      // 处理手机号脱敏显示
      if (col.key === 'phoneNumber') {
        return {
          ...col,
          render(row) {
            const phone = row[col.key] || ''
            if (phone.length === 11) {
              return phone.substring(0, 3) + '****' + phone.substring(7)
            }
            return phone || '-'
          }
        }
      }

      return col
    })
})

// 方法
const handleViewDetails = (member) => {
  emit('view-details', member)
}

const handleDeleteMember = (member) => {
  emit('delete-member', member)
}

const handleTableScroll = (e) => {
  emit('table-scroll', e)
}

// 横向滚动控制方法
const scrollToLeft = async () => {
  await waitForNextTick()
  const tableElement = getTableScrollElement()
  if (tableElement && tableElement.scrollWidth > tableElement.clientWidth) {
    tableElement.scrollTo({ left: 0, behavior: 'smooth' })
  }
}

const scrollToRight = async () => {
  await waitForNextTick()
  const tableElement = getTableScrollElement()
  if (tableElement && tableElement.scrollWidth > tableElement.clientWidth) {
    const maxScrollLeft = tableElement.scrollWidth - tableElement.clientWidth
    tableElement.scrollTo({ left: maxScrollLeft, behavior: 'smooth' })
  }
}

const scrollToCenter = async () => {
  await waitForNextTick()
  const tableElement = getTableScrollElement()
  if (tableElement && tableElement.scrollWidth > tableElement.clientWidth) {
    const maxScrollLeft = tableElement.scrollWidth - tableElement.clientWidth
    const centerPosition = maxScrollLeft / 2
    tableElement.scrollTo({ left: centerPosition, behavior: 'smooth' })
  }
}

const getTableScrollElement = () => {
  if (!tableRef.value) return null
  const tableEl = tableRef.value.$el
  const selectors = [
    '.n-data-table-base-table-body',
    '.n-data-table__main',
    '.n-data-table-wrapper',
    '.n-scrollbar-container',
    '.n-scrollbar-content'
  ]
  for (const selector of selectors) {
    const element = tableEl.querySelector(selector)
    if (element && element.scrollWidth > element.clientWidth) {
      return element
    }
  }
  return tableEl
}

const waitForNextTick = () => new Promise(resolve => setTimeout(resolve, 0))

// 暴露方法给父组件
defineExpose({
  scrollToLeft,
  scrollToRight,
  scrollToCenter,
  getTableScrollElement
})
</script>